<template>
  <div class="inner-container">
    <div class="left-container">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="90px"
      >
        <TabelBox ref="tempData" :tabel-box-data="TabelBoxData" />
        <el-row>
          <el-col :span="6">
            <el-form-item label="紧急程度" prop="urgent">
              <el-radio-group v-model="temp.urgent" :disabled="flowStatus > 1">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="1">紧急</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="申请原因" prop="reason">
              <el-input
                v-model.trim="temp.reason"
                :disabled="flowStatus > 1"
                type="textarea"
                placeholder="请输入内容"
                max-length="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <!-- <el-form-item v-if="flowStatus == 4" label="作废文件">
              <el-tag>{{ temp.documentName }}</el-tag>
            </el-form-item> -->
            <el-form-item
              v-if="flowStatus == 3 || (flowStatus == 1 && temp.result != 2)"
              label="文件管理员"
              prop="reviewer"
            >
              <el-tag
                v-for="(tag, index) in temp.reviewName"
                :key="index"
                :disable-transitions="false"
                class="tag"
              >
                {{ tag.userName }}
              </el-tag>
              <el-button
                size="mini"
                round
                circle
                icon="el-icon-plus"
                @click="openReview(3)"
              />
            </el-form-item>
            <el-form-item
              v-if="flowStatus == 2 && temp.result != 2"
              label="审批人"
              prop="reviewer"
            >
              <el-tag
                v-if="temp.reviewName"
                :disable-transitions="false"
                class="tag"
              >
                {{ temp.reviewName }}
              </el-tag>
              <el-button
                size="mini"
                round
                circle
                icon="el-icon-plus"
                @click="openReview(1)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              v-if="flowStatus > 1 && flowStatus < 4"
              label="处理意见"
              prop="reviewer"
            >
              <el-input v-model.trim="temp.opinion" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              v-if="flowStatus == 2 || flowStatus == 3"
              label="处理结果"
            >
              <el-radio-group v-model="temp.result" @change="reject">
                <el-radio :label="1">通过</el-radio>
                <el-radio :label="2">拒绝</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="flowStatus == 4" label="作废日期" prop="name">
          <el-date-picker
            v-model="temp.effectDate"
            type="date"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-row style="margin-bottom: 15px">
          <el-col :span="24">
            <el-button-group>
              <el-button
                size="small"
                type="primary"
                icon="el-icon-top button-icon"
                :disabled="impose"
                @click="handleSubmit"
                >提交</el-button
              >
              <!-- <el-button
                size="small"
                icon="el-icon-close button-icon"
                @click="handleClose"
                >取消</el-button
              > -->
            </el-button-group>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="right-container">
      <TimeLine :timeline-data="TimelineData" />
    </div>
    <SearchPersonnelType
      :search-personnel-type-data="SearchPersonnelTypeData"
      @dataList="dataList"
    />
    <SearchUserList
      :search-user-list-data="SearchUserListData"
      @SearchUserList="selectReviewUserList"
    />
    <SearchPersonnel
      :search-personnel-data="SearchPersonnelData"
      @dataListData="dataListData"
    />
  </div>
</template>

<script>
import {
  apply,
  approval,
  contentAudit,
  release
} from '@/api/xd/flow/flow_delete'
import { getDocumentParticulars } from '@/api/fd/folder'
import { getA_ZArray } from '@/utils'
import { getDocumentFlowPrintAndDrop } from '@/api/xd/documentFlow'

import SearchPersonnelType from '@/components/SearchUserType/index.vue'
import SearchUserList from '@/components/SearchUserList'
import TimeLine from '@/views/flow/components/Timeline'
import TabelBox from '../../components/TableBox/TableBox.vue'
import { mapGetters } from 'vuex'
import SearchPersonnel from '@/components/SearchUser/SearchPersonnel.vue'

export default {
  components: {
    SearchPersonnelType,
    SearchUserList,
    TimeLine,
    TabelBox,
    SearchPersonnel
  },
  data() {
    const PHASE_APPLY = 1
    const PHASE_CONTENT_AUDIT = 2
    // const PHASE_REVIEW = 3
    const PHASE_APPROVAL = 3
    const PHASE_RELEASE = 4
    const FLOW_TYPE_DELETE = 3
    return {
      flowStatusOptions: [
        {
          value: PHASE_APPLY,
          phaseName: '作废申请',
          phase: 'newApply',
          color: '#adaaa5'
        },
        { value: PHASE_CONTENT_AUDIT, phaseName: '文件审核', phase: 'audit' },
        // { value: PHASE_REVIEW, phaseName: '评审', phase: 'review' },
        { value: PHASE_APPROVAL, phaseName: '审批', phase: 'approve' },
        { value: PHASE_RELEASE, phaseName: '作废发行', phase: 'release' }
      ],
      title: '',
      flowStatus: 1,
      v1: 'A',
      v1Options: [],
      v2: 0,
      v2Options: [],
      temp: {
        flowType: FLOW_TYPE_DELETE,
        documentName: null,
        urgent: 0,
        documentVersion: null,
        previousDocumentVersion: null,
        reason: null,
        documentId: null,
        documentManagerUserId: 1,
        documentManagerUserGroupId: 1,
        // 修改
        dialogDocument: false,
        result: 1,
        reviewName: ''
      },
      rules: {
        documentCode: [
          { required: true, message: '文件编号不能为空', trigger: 'change' }
        ]
      },
      activities: [],
      userGroup: [],
      userGroupId: '',
      repository: [],
      repositoryId: '',
      options: [],
      dialogDocument: false,
      refresh: 0,
      uploadFolderTree: [],
      dialogReview: false,
      reviewData: [],
      reviewWindow: 0,
      particularsdocumentName: '',
      // 优化流程
      SearchPersonnelTypeData: {},
      dialogVisible: false,
      SearchPersonnelData: {},
      SearchUserListData: {},
      SelectGroupListData: {},
      trainName: '',
      documentCode: '',
      timeout: '',
      impose: false,
      TimelineData: {},
      TabelBoxData: {},
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      }
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },
  watch: {
    options: function () {
      ++this.refresh
    }
  },
  updated() {
    this.$emit('flowData', {
      flowStatus: this.flowStatus,
      documentCode: this.temp.documentCode
    })
  },
  mounted() {
    this.v1Options = getA_ZArray()
    for (let i = 1; i < 10; i++) {
      const c = i
      this.v2Options.push({ value: c, label: c })
    }
    if (this.$route.query.phase) {
      this.flowStatus = Number(this.$route.query.phase)
    }
    if (this.$route.params.documentFlowId) {
      this.getFlowData(this.$route.params.documentFlowId)
    }
    this.toTabelBoxData()
  },
  beforeUpdate() {
    this.TimelineFun()
  },
  methods: {
    // 表格数据
    toTabelBoxData() {
      this.TabelBoxData = {
        flowStatus: this.flowStatus,
        roles: this.roles,
        temp: [],
        type: 1
      }
    },
    // 时间线数据
    TimelineFun() {
      this.TimelineData = {
        documentFlowId: this.$route.params.documentFlowId,
        status: this.temp,
        flowStatusOptions: this.flowStatusOptions
      }
    },
    selectReviewUserList(val) {
      this.reviewData = val
    },

    // 拒绝驳回
    reject(lab) {
      if (lab == 1) {
        this.temp.result = 2
      } else {
        this.temp.result = 1
      }
      this.$forceUpdate()
    },
    async getFlowData(documentFlowId) {
      if (documentFlowId != 0) {
        await getDocumentFlowPrintAndDrop({
          documentFlowId: documentFlowId
        }).then((res) => {
          console.log(res, '返回数据')
          this.temp = Object.assign(res.data)
          this.TabelBoxData = {
            flowStatus: this.flowStatus,
            roles: this.roles,
            temp: res.data.documentFlowInfoList,
            type: 1
          }

          this.temp.result = 1
          this.temp.urgent = parseInt(this.temp.urgent)
        })
      }
      if (this.flowStatus !== 1) {
        // await nodeHandleByCode({
        //   code: this.temp.documentCode,
        //   phase: this.temp.phase
        // }).then((res) => {
        //   ;(this.temp.reviewName = res.data[0].handleUserName),
        //     (this.temp.reviewId = res.data[0].handleUserId)
        //   this.$forceUpdate()
        // })
      }
    },
    async handleSubmit() {
      if (this.flowStatus === 1) {
        const res = await this.$refs['tempData'].backTempData()
        if (res.valid) {
          const documentFlowInfoList = Array.from(res.documentFlowInfoList)
          let batchType = 0
          if (documentFlowInfoList.length > 1) {
            batchType = 2
          }
          const newDocumentFlowInfoList = []
          documentFlowInfoList.forEach((e) => {
            newDocumentFlowInfoList.push({
              documentCode: e.documentCode,
              documentVersion: e.documentVersion,
              documentName: e.documentName,
              documentId: e.documentId,
              documentLevel: e.documentLevel,
              documentProperty: e.documentProperty
            })
          })
          console.log(documentFlowInfoList, 'documentFlowInfoList')
          var data = {
            nextHandleUserId: this.temp.reviewId,
            reason: this.temp.reason,
            urgent: this.temp.urgent,
            documentFlowInfoList: newDocumentFlowInfoList,
            batchType: batchType
          }
        } else {
          return
        }
        if (!data.reason) {
          this.$message.warning('申请原因不可为空')
          return
        }
        if (!data.nextHandleUserId) {
          this.$message.warning('审核人不可为空')
          return
        }
        if (!data.reason) {
          this.$message.warning('申请内容不可为空')
          return
        }
        apply(data).then(() => {
          this.$message.success('操作成功')
          this.$router.push('/unread')
        })
      }
      if (this.flowStatus === 2) {
        const data = {
          documentFlowId: this.temp.documentFlowId,
          nextHandleUserId: this.temp.reviewId,
          opinion: this.temp.opinion,
          result: this.temp.result
        }
        if (data.result == 1) {
          if (!data.nextHandleUserId) {
            this.$message.warning('审批人不可为空')
            return
          }
        }
        if (!data.opinion) {
          this.$message.warning('处理意见不可为空')
          return
        }
        if (data.result == null) {
          this.$message.warning('处理结果不可为空')
          return
        }
        contentAudit(data).then(() => {
          this.$message.success('操作成功')
          this.$store.commit(
            'message/FLOW_COUNT',
            this.$store.state.message.flowCount - 1
          )
          this.$router.push('/unread')
        })
      }

      // if (this.flowStatus === 3) {
      //   const data = {
      //     documentFlowId: this.temp.documentFlowId,
      //     opinion: this.temp.opinion
      //   }
      //   if (!data.documentFlowId) {
      //     this.$message.warning('流程标识不可为空')
      //     return
      //   }
      //   if (!data.opinion) {
      //     this.$message.warning('评审意见不可为空')
      //     return
      //   }
      //   review(data).then((res) => {
      //     this.$message.success('操作成功')
      //     this.$store.commit(
      //       'message/FLOW_COUNT',
      //       this.$store.state.message.flowCount - 1
      //     )
      //     this.$router.push('/unread')
      //   })
      // }

      if (this.flowStatus === 3) {
        this.temp.documentVersion = this.v1 + this.v2
        const data = {
          documentFlowId: this.temp.documentFlowId,
          nextHandleUserId: this.temp.reviewId,
          opinion: this.temp.opinion,
          result: this.temp.result
        }
        if (data.result == 1) {
          if (!data.nextHandleUserId) {
            this.$message.warning('审批人不可为空')
            return
          }
        }
        if (!data.opinion) {
          this.$message.warning('处理内容不可为空')
          return
        }
        if (data.result == null) {
          this.$message.warning('处理结果不可为空')
          return
        }

        approval(data).then(() => {
          this.$message.success('操作成功')
          this.$store.commit(
            'message/FLOW_COUNT',
            this.$store.state.message.flowCount - 1
          )
          this.$router.push('/unread')
        })
      }
      if (this.flowStatus === 4) {
        const data = {
          documentFlowId: this.temp.documentFlowId,
          documentId: this.temp.documentId,
          effectDate: this.temp.effectDate,
          opinion: this.temp.opinion || '',
          receiveUserGroupIdList: [],
          receiveUserIdList: []
        }
        if (!data.effectDate) {
          this.$message.warning('作废日期不可为空')
          return
        }
        if (data.documentId == 0) {
          this.$message.warning('文件不可为空')
          return
        }
        release(data).then(() => {
          this.$message.success('操作成功')
          this.$router.push('/unread')
        })
      }
    },
    handleClose() {
      this.$router.push({ path: '/unread' })
    },
    async getDocumentParticulars() {
      const particularsdata = await getDocumentParticulars({
        documentId: this.temp.documentId
      })
      this.temp.documentCode = particularsdata.data.documentCode
      this.particularsdocumentName = particularsdata.data.documentName
      this.v2 = particularsdata.data.version
    },
    dataList(val) {
      this.temp.reviewName = val[0].userName
      this.temp.reviewId = val[0].userId
      this.$forceUpdate()
    },
    // 》》》》》》》》》》》》》》》》》》》》》》》》》》
    // 优化流程所有人员
    openReview(val, type, title) {
      // 0为角色 1为角色（总经理，总监） 3为架构 4为架构多选 5部门多选
      this.reviewWindow = val
      if (val == 0) {
        console.log(this.temp, '管理员')
        if (
          this.temp.documentLevelNum == 1 ||
          this.temp.documentLevelNum == 2
        ) {
          type = 'management-representative'
          title = '管理者代表'
        } else {
          type = 'qa'
          title = 'QA'
        }
        this.SearchPersonnelTypeData = {
          val: val,
          type: type,
          dialogVisible: true,
          title: title
        }
      } else if (val == 1) {
        if (
          this.temp.documentLevelNum == 1 ||
          this.temp.documentLevelNum == 2
        ) {
          type = 'president'
          title = '总经理'
        } else {
          type = 'director'
          title = '总监'
        }
        this.SearchPersonnelTypeData = {
          val: val,
          type: type,
          dialogVisible: true,
          title: title
        }
      } else if (val == 3) {
        this.SearchPersonnelData = {
          dialogVisible: true
        }
      } else if (val == 4) {
        this.SearchUserListData = {
          dialogVisible: true
        }
      } else if (val == 5) {
        this.SelectGroupListData = {
          dialogVisible: true
        }
      }
    },
    dataListData(data) {
      if (data) {
        const dataList = []
        data.forEach((res) => {
          dataList.push({ userName: res.label })
        })
        if (this.temp.trainFlag) {
          this.trainName = data[0].label
          this.temp.reviewId = data[0].id
          return
        }
        this.temp.reviewName = dataList
        this.temp.reviewId = data[0].id
        this.$forceUpdate()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.inputbox {
  display: flex;
  .input-el {
    text-align: center;
    margin-right: 10px;
  }
}
.input {
  width: 50px;
  text-align: center;
}
.tag {
  margin-right: 10px;
}
.label {
  width: 39%;
}
.buttonleft {
  margin-left: 85%;
}

.inner-container {
  display: -webkit-flex;
  display: flex;
  flex-direction: row;
}

.left-container {
  width: calc(100% - 300px);
}

.right-container {
  width: 300px;

  .el-timeline {
    .el-timeline-item {
      height: 56px;
      line-height: 56px;

      p {
        height: 16px;
        line-height: 16px;
        font-size: 13px;
      }
    }
  }
}
</style>
